package com.yaxin.oss.core;

import com.yaxin.oss.properties.OssProxyProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author lguoji
 */
@Service
public class OssUrlUtil {

    private final OssProxyProperties ossProxyProperties;

    public OssUrlUtil(OssProxyProperties ossProxyProperties) {
        this.ossProxyProperties = ossProxyProperties;
    }

    public String convertToProxyUrl(String originUrl) {
        String origin = StringUtils.stripEnd(ossProxyProperties.getMinioOriginHost(), "/");
        String proxy = StringUtils.stripEnd(ossProxyProperties.getProxyHost(), "/");
        if (StringUtils.isBlank(originUrl) || !originUrl.startsWith(origin)) {
            return originUrl;
        }
        return originUrl.replaceFirst(Pattern.quote(origin), Matcher.quoteReplacement(proxy));
    }


    /**
     * 将富文本中的 MinIO 原始地址替换为代理地址（用于展示场景）
     *
     * @param htmlContent 原始 HTML 内容
     * @return 替换后的 HTML 内容
     */
    public String replaceMinioOriginWithProxy(String htmlContent) {
        if (StringUtils.isBlank(htmlContent)) {
            return htmlContent;
        }

        String originHost = StringUtils.stripEnd(ossProxyProperties.getMinioOriginHost(), "/");
        String proxyHost = StringUtils.stripEnd(ossProxyProperties.getProxyHost(), "/");

        return htmlContent.replaceAll(
            Pattern.quote(originHost),
            Matcher.quoteReplacement(proxyHost)
        );
    }

    /**
     * 将富文本中的 MinIO 代理地址替换为原始地址（用于存储或还原场景）
     *
     * @param htmlContent HTML 内容
     * @return 替换后的 HTML 内容
     */
    public String replaceMinioProxyWithOrigin(String htmlContent) {
        if (StringUtils.isBlank(htmlContent)) {
            return htmlContent;
        }

        String originHost = StringUtils.stripEnd(ossProxyProperties.getMinioOriginHost(), "/");
        String proxyHost = StringUtils.stripEnd(ossProxyProperties.getProxyHost(), "/");

        return htmlContent.replaceAll(
            Pattern.quote(proxyHost),
            Matcher.quoteReplacement(originHost)
        );
    }



}
